package com.tau.egonetwork.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;

public class Log {

	private static boolean opened = false;
	private static PrintWriter writer = null;
	
	private Log() { }
	
	static {
		
		//if DIR doesn't exist, create it:
		File dir = new File(Configurations.logsDirectory());
		if (!dir.exists()) {
			dir.mkdir();
		}

		Calendar calendar = Calendar.getInstance();
		String filename = Configurations.logsDirectory() +
				File.separator + "EgoNetworkLog_"
				+ String.format("%04d%02d%02d%02d%02d%02d",
						calendar.get(Calendar.YEAR),
						calendar.get(Calendar.MONTH),
						calendar.get(Calendar.DAY_OF_MONTH),
						calendar.get(Calendar.HOUR),
						calendar.get(Calendar.MINUTE),
						calendar.get(Calendar.SECOND)) 
				+ ".log";
		
		try {
			writer = new PrintWriter(filename, "UTF-8");
		} catch (FileNotFoundException e) {
			System.out.println("Warning: could not create log file!");
		} catch (UnsupportedEncodingException e) {
			System.out.println("Warning: could not create log file!");
		}
		
	}
	
	public static void startLog() {
		
		//cannot only call start log once!
		
		if (opened || writer == null)
			return;
		
		opened = true;
		
		writeLineToLog("Egocenteric Network Starting...");
		writeLineToLog("---------------------------------------");
	}
	
	public static void writeLineToLog(String line) {
		
		if (writer == null) return;
		
		synchronized(writer) {
			Calendar calendar = Calendar.getInstance();
			writer.write("[" +
					String.format("%02d:%02d:%02d:%04d",
							calendar.get(Calendar.HOUR),
							calendar.get(Calendar.MINUTE),
							calendar.get(Calendar.SECOND),
							calendar.get(Calendar.MILLISECOND))
					+ "] " + line + String.format("%n"));
		}
	}
	
	public static void writeExceptionToLog(Exception e) {
		
		if (writer == null) return;
		
		synchronized(writer) {
			Calendar calendar = Calendar.getInstance();
			writer.write("[" +
					String.format("%02d:%02d:%02d:%04d",
							calendar.get(Calendar.HOUR),
							calendar.get(Calendar.MINUTE),
							calendar.get(Calendar.SECOND),
							calendar.get(Calendar.MILLISECOND))
					+ "] Exception thrown: " + e.getMessage() + String.format("%n"));
			
			for (StackTraceElement ste : e.getStackTrace()) {
				writer.write(ste.toString() + String.format("%n"));
			}
			
			if (e.getCause() != null) {
				writer.write("Cause of exception: " + e.getCause().getMessage() + String.format("%n"));
				for (StackTraceElement ste : e.getCause().getStackTrace()) {
					writer.write(ste.toString() + String.format("%n"));					
				}
			}
			
			//when writing an exception, flush so the log will most
			//definitely hold this information!:
			writer.flush();
		}

		
	}
	
	public static void closeLog() {
		synchronized(writer) {
			writer.flush();
			writer.close();
		}
	}
}
